const fs = require("fs")
// 关于faker.js的使用详见: https://www.npmjs.com/package/faker
const faker = require("faker")
faker.locale = "zh_CN"

module.exports = {
  "GET /api/detail/:id": (req, res) => {
    setTimeout(() => {
      res.send({
        code: "200",
        data: {
          id: req.params.id,
          name: faker.name.findName(),
          email: faker.internet.email()
        }
      })
    }, 500)
  },

  "GET /api/list": (req, res) => {
    // 获取 /api/list?size=10&page=1
    console.log(req.params)
    console.log(req.query)
    const size = req.query.size
    const page = req.query.page
    const arr = new Array(10).fill(true).map(() => {
      return {
        id: faker.datatype.number(),
        sex: faker.datatype.number(1),
        name: faker.name.findName(),
        email: faker.internet.email()
      }
    })
    res.send({
      code: "200",
      data: {
        size,
        page,
        list: arr
      }
    })
  },

  "POST /api/add": (req, res) => {
    console.log("---->", req.body)
    setTimeout(() => {
      res.send({ code: "200" })
    }, 400)
  },

  "POST /api/upload": (req, res) => {
    console.log(req.file)
    console.log(req.files)
    console.log(req.name)
    console.log(req.params)
    console.log(req.query)
    setTimeout(() => {
      res.send({ status: "200" })
    }, 400)
  },

  "POST /api/download": (req, res) => {
    // 如果是linux则表示根目录下的对应物理文件, 如果是windows则表示是对应盘符下的物理文件
    var path = `/test/test.xlsx`
    res.setHeader("Content-type", "application/octet-stream")
    res.setHeader("Content-Disposition", `attachment;filename=test.xlsx`)
    var fileStream = fs.createReadStream(path)
    fileStream.on("data", function (data) {
      res.write(data, "binary")
    })
    fileStream.on("end", function () {
      res.end()
      console.log("The file has been downloaded successfully!")
    })
  },

  "POST /api/download/error": (req, res) => {
    res.send({ code: 500, msg: "下载出错了" })
  },

  "POST /api/exp": (req, res) => {
    res.send({ code: 500, msg: "已知的业务异常" })
  },

  "POST /api/error": (req, res) => {
    res.status(500).json({ code: 500, msg: "服务出错" })
  },

  "POST /api/403": (req, res) => {
    res.status(403).json({ code: 403, msg: "没权限" })
  },
  "POST /api/201": (req, res) => {
    res.status(201).json({ code: 201 })
  }
}
